Popular Searches
Popular Course Categories
Popular Courses

Understanding Java Keywords and Identifiers

Understanding Java Keywords and Identifiers

Java Syntax, Variables, and Data Types

Understanding Java Keywords and Identifiers

Course: Core Java Training

Topic: Understanding Java Keywords and Identifiers

Course Link: Core Java Training Course

Demo Link: Register for a Free Course Demo

JustAcademy Website: Visit JustAcademy


1. Introduction to Java Keywords and Identifiers

Java is a strongly typed, object-oriented programming language that follows specific rules for writing readable and valid programs. Two fundamental elements of Java syntax are keywords and identifiers.

Keywords are reserved words with predefined meanings in Java. Identifiers are names created by programmers to identify program elements such as variables, methods, classes, interfaces, packages, and constants.

Understanding the difference between these concepts helps developers write syntactically correct, readable, and maintainable Java code.

Example

public class Student {
    int studentAge = 20;

    public void displayAge() {
        System.out.println(studentAge);
    }
}

In this example:

  • public, class, int, and void are Java keywords.
  • Student, studentAge, and displayAge are identifiers.
  • 20 is an integer literal.

2. Learning Objectives

After completing this topic, you should be able to:

  • Define Java keywords and identifiers.
  • Understand the purpose of reserved words in Java.
  • Identify commonly used Java keywords.
  • Understand the rules for creating valid identifiers.
  • Differentiate keywords from identifiers, literals, and operators.
  • Apply Java naming conventions to variables, methods, classes, and constants.
  • Recognize and correct common syntax errors involving keywords and identifiers.

3. What Are Java Keywords?

Java keywords are reserved words that have predefined meanings in the language. The Java compiler recognizes these words and interprets them according to the language syntax.

Because keywords are reserved, programmers cannot use them as ordinary identifiers for variables, classes, methods, or other named program elements.

Examples of Java Keywords

int marks = 85;
if (marks >= 40) {
    System.out.println("Pass");
}

Here, int declares an integer variable, while if introduces a conditional statement. Both words have special meanings in Java.

Important Characteristics of Keywords

  • Keywords have predefined meanings in Java.
  • They form part of Java's language syntax.
  • They cannot be used as ordinary identifiers.
  • Java is case-sensitive, so changing capitalization changes how a word is interpreted.
  • Some keywords are used for data types, access control, object creation, inheritance, exception handling, and program flow.

4. Categories of Java Keywords

Java keywords can be grouped by their purpose. The following table summarizes commonly used categories and examples.

Category Keywords Purpose
Data types int, double, char, boolean, byte, short, long, float Declare primitive data types.
Access modifiers public, private, protected Control access to classes and members.
Class and object concepts class, new, this, super, extends, implements, instanceof Define classes, create objects, and support inheritance and type checks.
Decision-making if, else, switch, case, default Choose between execution paths.
Loops for, while, do, break, continue Repeat operations or alter loop execution.
Methods and return values void, return Declare methods that return no value and transfer values or control.
Exception handling try, catch, finally, throw, throws Handle and declare exceptions.
Packages and imports package, import Organize classes and make types available by name.
Concurrency synchronized, volatile Support particular thread-safety and memory-visibility behaviors.
Other language features static, final, abstract, native, strictfp Declare class-level members, restrict reassignment or inheritance, or control other language behaviors.

Note: This is a practical selection, not an exhaustive list. The exact language specification includes additional keywords and contextual rules. Some words, such as var and yield, have context-dependent uses, while const and goto are reserved but unused.

5. Frequently Used Java Keywords Explained

5.1 The class Keyword

The class keyword declares a class, which defines the structure and behavior of objects.

class Employee {
    String name;
    int employeeId;
}

Employee is the class identifier, and class is the keyword.

5.2 The public Keyword

The public access modifier makes a class or member accessible wherever the applicable Java access rules permit.

public class Main {
    public void showMessage() {
        System.out.println("Welcome to Java");
    }
}

5.3 The static Keyword

The static keyword declares a class-level member rather than an instance-specific member.

class Counter {
    static int count = 0;
}

The variable count belongs to the Counter class rather than to each individual object.

5.4 The final Keyword

The final keyword restricts reassignment of a variable, overriding of a method, or inheritance from a class, depending on where it is used.

final int MAX_ATTEMPTS = 3;

Once initialized, this local variable cannot be assigned another value.

5.5 The new Keyword

The new keyword creates an object or array and returns a reference to it.

Student student = new Student();

Here, new creates a Student object, and student is the identifier for the reference variable.

5.6 The this Keyword

The this keyword refers to the current object in an instance context.

class Student {
    String name;

    Student(String name) {
        this.name = name;
    }
}

this.name refers to the object's field, while name on the right side refers to the constructor parameter.

5.7 The if and else Keywords

These keywords execute different blocks based on whether a condition evaluates to true or false.

int age = 19;

if (age >= 18) {
    System.out.println("Eligible");
} else {
    System.out.println("Not eligible");
}

5.8 The return Keyword

The return keyword ends a method's execution and can provide a result to the caller.

int add(int a, int b) {
    return a + b;
}

6. What Are Java Identifiers?

Identifiers are user-defined names used to identify elements in a Java program. They help programmers refer to variables, methods, classes, interfaces, packages, enum constants, and other declarations.

Example

class Product {
    String productName;
    double price;

    void displayProduct() {
        System.out.println(productName + ": " + price);
    }
}

In this example:

  • Product identifies a class.
  • productName identifies a field.
  • price identifies another field.
  • displayProduct identifies a method.

Characteristics of Identifiers

  • Identifiers are chosen by the programmer.
  • They must follow Java's identifier rules.
  • They cannot be reserved keywords.
  • They are case-sensitive.
  • Meaningful identifiers improve readability and maintainability.

7. Rules for Creating Valid Java Identifiers

Rule 1: An Identifier Cannot Begin with a Digit

A Java identifier cannot start with a numeric digit.

// Invalid
int 2marks = 90;

// Valid
int marks2 = 90;
int marks2026 = 95;

Rule 2: Identifiers Can Use Letters, Digits, Underscores, and Dollar Signs

Java identifiers can contain letters, digits, underscores (_), dollar signs ($), and many Unicode characters that qualify under Java's identifier rules. An underscore or dollar sign may be used at the beginning, subject to the language rules.

int studentAge = 20;
int student_age = 20;
int student2 = 20;
int $amount = 500;
int _score = 90;

Although forms such as $amount and _score can be legal identifiers, ordinary application code usually avoids leading dollar signs and underscores unless a project has a specific convention.

Rule 3: Spaces Are Not Allowed

Identifiers cannot contain spaces. Use camelCase or another consistent naming convention instead.

// Invalid
int student age = 20;

// Valid
int studentAge = 20;
int student_age = 20;

Rule 4: Keywords Cannot Be Used as Identifiers

// Invalid
int class = 10;
String public = "Java";

// Valid
int classCount = 10;
String accessLevel = "public";

A keyword can appear inside a longer identifier, such as classCount, because the complete name is not the reserved word class.

Rule 5: Identifiers Are Case-Sensitive

Java treats uppercase and lowercase letters as different characters. Therefore, identifiers such as total, Total, and TOTAL are distinct names.

int total = 100;
int Total = 200;

System.out.println(total); // 100
System.out.println(Total); // 200

Even though this is legal, using names that differ only by capitalization can confuse readers and should generally be avoided.

Rule 6: Avoid Special Symbols That Are Not Allowed

Characters such as @, #, %, and hyphens cannot be used as ordinary identifier characters under Java's identifier rules.

// Invalid
int student-age = 20;
int total#marks = 90;

// Valid
int studentAge = 20;
int totalMarks = 90;

Rule 7: Reserved Words and Literal Tokens Cannot Be Used as Ordinary Identifiers

Besides keywords, the boolean literals true and false, and the null literal null, cannot be declared as ordinary identifiers. The standalone underscore (_) is also reserved as a keyword in modern Java and cannot be used alone as an identifier.

// Invalid in modern Java
int _ = 10;
boolean true = false;

// Valid
int _score = 10;
boolean isActive = false;

8. Java Naming Conventions for Identifiers

Naming conventions are recommended practices that make Java code consistent and easier to understand. They are not all compiler-enforced rules.

Program Element Recommended Convention Example
Class PascalCase StudentDetails
Interface PascalCase PaymentService
Variable camelCase studentAge
Method camelCase calculateTotal()
Constant UPPER_SNAKE_CASE MAX_RETRY_COUNT
Package Lowercase, often reverse-domain style com.example.student
Enum type PascalCase OrderStatus
Enum constant UPPER_SNAKE_CASE ORDER_PLACED

8.1 Camel Case

In camelCase, the first word starts with a lowercase letter, and each following word begins with an uppercase letter. It is commonly used for variables and methods.

String firstName = "Aarav";
int totalMarks = 450;

void calculateAverage() {
    System.out.println("Calculating average");
}

8.2 Pascal Case

In PascalCase, each word begins with an uppercase letter. It is commonly used for class, interface, and enum type names.

class BankAccount {
}

interface DataProcessor {
}

enum PaymentStatus {
    PENDING,
    COMPLETED
}

8.3 Upper Snake Case

Upper snake case uses uppercase letters with underscores separating words. It is commonly used for constants.

static final int MAX_USERS = 100;
static final double PI_VALUE = 3.14159;

8.4 Choosing Meaningful Names

Good identifiers explain what the program element represents or does.

// Poor naming
int x = 500;
void calc() {
}

// Better naming
int accountBalance = 500;
void calculateMonthlyInterest() {
}

Short names can be suitable for small, familiar contexts such as loop counters, but descriptive names are preferable for most business logic.

9. Difference Between Java Keywords and Identifiers

Basis Keywords Identifiers
Meaning Reserved words with predefined meanings. Names used to identify declared program elements.
Who defines them? Defined by the Java language. Usually chosen by the programmer.
Can they be renamed? No; their language meanings are fixed. Names can be changed by editing the declarations and their references.
Can they be used as variable names? No. Yes, if they satisfy the rules and do not conflict with the declaration context.
Examples class, int, return Student, age, calculateTotal
Purpose Define language structure and behavior. Give names to program elements.

10. Keywords, Identifiers, Literals, and Operators

Java programs contain several kinds of tokens. Knowing how they differ helps when reading code and diagnosing compiler errors.

int score = 95 + 5;
  • int is a keyword.
  • score is an identifier.
  • 95 and 5 are integer literals.
  • = and + are operators.
  • ; is a statement terminator.
Token Type Description Examples
Keyword Reserved word with a language-defined role. int, if, return
Identifier Name of a declaration or program element. score, Student
Literal A fixed value written directly in code. 100, "Hello", true
Operator Symbol or token that performs an operation. +, ==, =

11. Contextual Keywords and Special Cases

Not every word that looks important in Java behaves like a traditional reserved keyword in every context. Some terms have special meaning only in particular syntactic positions.

  • var allows local variable type inference in supported declarations. It is not a general-purpose type name that can be used everywhere.
  • record declares record types in supported Java versions, but its treatment differs from traditional reserved keywords.
  • yield is used in certain switch expressions and has context-sensitive rules.
  • permits and non-sealed are associated with sealed classes and interfaces.
  • const and goto are reserved but are not used as ordinary Java language features.

When working with newer Java versions, check the language version used by your project because some syntax and contextual rules depend on that version.

12. Common Errors Involving Keywords and Identifiers

Error 1: Using a Keyword as a Variable Name

// Incorrect
int return = 5;

// Correct
int returnValue = 5;

Why it fails: return is a reserved keyword used to return control or a value from a method.

Error 2: Starting an Identifier with a Number

// Incorrect
int 1stNumber = 10;

// Correct
int firstNumber = 10;

Error 3: Including Spaces in an Identifier

// Incorrect
String first name = "Riya";

// Correct
String firstName = "Riya";

Error 4: Inconsistent Capitalization

int totalMarks = 90;
System.out.println(TotalMarks); // Compilation error

Why it fails: totalMarks and TotalMarks are different identifiers. Java is case-sensitive.

Error 5: Using Invalid Symbols

// Incorrect
double total-price = 99.50;

// Correct
double totalPrice = 99.50;

Error 6: Using an Identifier Before Declaring It

// Incorrect
System.out.println(studentName);
String studentName = "Aarav";

In this example, the local variable is used before its declaration. Declare it before using it:

String studentName = "Aarav";
System.out.println(studentName);

13. Complete Java Example: Keywords and Identifiers

The following program demonstrates several keywords and identifiers in a simple class.

public class StudentReport {
    private String studentName;
    private int marks;

    public StudentReport(String studentName, int marks) {
        this.studentName = studentName;
        this.marks = marks;
    }

    public void displayResult() {
        if (marks >= 40) {
            System.out.println(studentName + " has passed.");
        } else {
            System.out.println(studentName + " has not passed.");
        }
    }

    public static void main(String[] args) {
        StudentReport report = new StudentReport("Riya", 85);
        report.displayResult();
    }
}

Keyword Identification

  • public and private are access modifiers.
  • class declares a class.
  • String is the name of a reference type, not a Java keyword.
  • int declares integer values.
  • this refers to the current object.
  • if and else control conditional execution.
  • void indicates that a method does not return a value.
  • static declares the class-level main method.
  • new creates a new object.

Identifier Identification

  • StudentReport is the class identifier.
  • studentName and marks are field and parameter identifiers, depending on their declaration.
  • displayResult and main are method identifiers.
  • report and args are identifiers.

Expected Output

Riya has passed.

14. Best Practices for Using Keywords and Identifiers

  • Learn frequently used keywords and their intended purposes.
  • Never use reserved keywords as ordinary names.
  • Choose descriptive identifiers that communicate meaning.
  • Use camelCase for variables and methods.
  • Use PascalCase for class, interface, and enum type names.
  • Use uppercase snake case for constants.
  • Avoid names that differ only in capitalization.
  • Avoid unnecessary abbreviations and ambiguous single-letter names in business logic.
  • Follow the naming standards already established by your team or project.
  • Use an IDE to identify syntax errors, rename symbols safely, and maintain consistent formatting.

15. Practical Exercises

Exercise 1: Identify Keywords and Identifiers

Review the following code and identify its keywords, identifiers, literals, and operators.

public class Book {
    int price = 500;

    void showPrice() {
        System.out.println(price);
    }
}

Exercise 2: Correct Invalid Identifiers

Correct the following declarations:

int 3students = 30;
String class = "Java";
double total-price = 250.75;
int student age = 21;

Possible corrected version:

int studentCount = 30;
String className = "Java";
double totalPrice = 250.75;
int studentAge = 21;

Exercise 3: Apply Naming Conventions

Rewrite these names using conventional Java naming:

  • student_details as a class name.
  • CalculateTotal as a method name.
  • maxValue as a constant name.
  • ORDERSTATUS as an enum type name.

Possible answers: StudentDetails, calculateTotal(), MAX_VALUE, and OrderStatus.

Exercise 4: Build a Simple Employee Program

Create an Employee class containing employee name, employee ID, and salary. Add a method that displays the details. Identify all keywords and identifiers in your program.

16. Interview Questions and Answers

Q1. What is a keyword in Java?

Answer: A keyword is a reserved word with a predefined meaning in the Java language, such as class, int, or return.

Q2. What is an identifier in Java?

Answer: An identifier is a name used to identify a program element, such as a variable, method, class, or interface.

Q3. Can a Java keyword be used as a variable name?

Answer: No. Reserved keywords cannot be used as ordinary variable names or other identifiers.

Q4. Is Java case-sensitive?

Answer: Yes. Names such as age and Age are treated as different identifiers.

Q5. Can an identifier start with a number?

Answer: No. A valid Java identifier cannot begin with a digit.

Q6. Can an identifier contain an underscore?

Answer: Yes. An underscore can be used within an identifier, such as student_age. However, the standalone underscore is reserved in modern Java and cannot be used alone as an identifier.

Q7. What is the difference between a keyword and an identifier?

Answer: A keyword has a language-defined meaning, while an identifier is a name used to identify a declared program element.

Q8. What is camelCase?

Answer: CamelCase starts with a lowercase letter and capitalizes the first letter of each subsequent word, such as calculateTotal.

Q9. What naming convention is used for Java classes?

Answer: PascalCase is conventionally used for class names, such as EmployeeDetails.

Q10. Are String and int both keywords?

Answer: No. int is a Java keyword, whereas String is the name of a class in the Java standard library.

Q11. Can an identifier contain digits?

Answer: Yes, an identifier can contain digits after its first character, such as student2.

Q12. What are naming conventions?

Answer: Naming conventions are recommended practices for naming program elements consistently, improving readability and collaboration.

17. Quick Revision Checklist

  • Keywords are reserved words with predefined meanings.
  • Identifiers are names given to program elements.
  • Java is case-sensitive.
  • Identifiers cannot begin with digits or contain spaces.
  • Reserved keywords cannot be used as ordinary identifiers.
  • Use camelCase for variables and methods.
  • Use PascalCase for classes and interfaces.
  • Use uppercase snake case for constants.
  • String is a class name, while int is a keyword.
  • Descriptive identifiers make code easier to read and maintain.

18. Conclusion

Java keywords and identifiers are essential building blocks of every Java program. Keywords define the language's structure and behavior, while identifiers provide meaningful names for classes, variables, methods, and other program elements. Learning the rules for valid identifiers and following standard naming conventions helps prevent compilation errors and improves code quality.

Practice identifying keywords and identifiers in real Java programs, correct invalid declarations, and use consistent naming conventions as you move on to data types, operators, control statements, methods, and object-oriented programming.

To continue learning, explore the Core Java Training Course, visit the course demo registration page, or browse the JustAcademy website.

whatsapp